# coding: utf-8

from vec2 import vec2
from typing import Sequence


class SvgImage:
    def __init__(self, size: vec2, margin: float = 0):
        self.m_size = size
        self.m_margin = margin
        self.m_data = []

    def draw_polyline(self, points: Sequence[vec2], color: str = "black"):

        # points = [p if p is not None else vec2() for p in points]
        # # if len(points) < 2:
        # #     return  # 不绘制折线
        # print('============', points)            ### 之前有
        # print(points[0], points[1])
        for i in range(len(points)):
            if points[i] is None:
                # points[i] = vec2(455.0, 2765.0)  ##22  缺少的111
                # points[i] = vec2(1385.0, 4195.0)   ##18  缺少的94
                print("在点列表中发现 None")
            # else:
            # print(f"点： {points[i].x}, {points[i].y},")
        points_str = " ".join([f"{p.x},{p.y}" for p in points])
        self.m_data.append(
            f'<polyline points="{points_str}" stroke="{color}" fill="none" />'
        )

    def draw_circle(self, center: vec2, r: float, color: str = "black"):
        cx, cy = center.x, center.y
        self.m_data.append(
            f'<circle cx="{cx}" cy="{cy}" r="{r}" stroke="{color}" stroke-width="1" fill="white" />'
        )

    def draw_text(self, pos: vec2, text: str, size: float, color: str = "black"):
        x, y = pos.x, pos.y
        self.m_data.append(
            f'<text x="{x}" y="{y}" fill="{color}" dominant-baseline="middle" text-anchor="middle" font-size="{size}" font-family="Times,serif">{text}</text>'
        )

    def draw_polygon(self, points: Sequence[vec2], color: str = "black"):
        points_str = " ".join([f"{p.x},{p.y}" for p in points])
        self.m_data.append(
            f'<polygon points="{points_str}" stroke="{color}" fill="{color}" />'
        )

    def draw_arrow(self, from_: vec2, to: vec2, size: float, color: str = "black"):
        dir1 = dir = from_ - to

        dir = dir.normalized()
        # print('from_',from_,'to',to)
        # print('to + size * dir.rotate(20)',to + size * dir.rotate(20))
        # print('to + size * dir.rotate(-20)',to + size * dir.rotate(-20))
        # print('size',size)
        a1 = to + dir1 * 0.5
        a2 = to + dir1 * 0.5 + size * dir.rotate(20)
        a3 = to + dir1 * 0.5 + size * dir.rotate(-20)
        # self.draw_polygon([to, to + size * dir.rotate(20),
        #                   to + size * dir.rotate(-20)], color)
        self.draw_polygon([a1, a2, a3], color)

    def add_image(self, img: "SvgImage"):
        self.m_data.append(
            f"<g transform='translate({self.m_size[0] + img.m_margin}, {img.m_margin})'>"
        )
        self.m_data.extend(img.m_data)
        self.m_data.append("</g>")
        self.m_size = (
            self.m_size[0] + img.m_size[0] + 2 * img.m_margin,
            max(self.m_size[1], img.m_size[1] + 2 * img.m_margin),
        )

    def save(self, filename: str):
        with open(filename, "w") as file:
            w = self.m_size.x + 2 * self.m_margin
            h = self.m_size.y + 2 * self.m_margin

            file.write("<svg xmlns='http://www.w3.org/2000/svg'\n")
            # \t 转义字符，表示一个制表符（tab）
            file.write(f"\twidth='{w}pt' height='{h}pt'\n")
            file.write(f"\tviewBox='0 0 {w} {h}'>\n")

            # draw a background polygon
            file.write("<polygon fill='white' stroke='transparent' ")
            file.write(f"points='0,0 0,{h} {w},{h} {w},0'/>\n")

            file.write(f"<g transform='translate({self.m_margin}, {self.m_margin})'>\n")
            file.write("\n".join(self.m_data))
            file.write("\n")
            file.write("</g>\n")
            file.write("</svg>\n")


class svg_file:
    def __init__(self, filename: str):
        self.m_file = open(filename, "w")
        self.m_file.write("<svg xmlns='http://www.w3.org/2000/svg'>\n")
        self.m_size = vec2()

    def __del__(self):
        self.m_file.write("</svg>\n")
        self.m_file.close()

    def add_image(self, img: SvgImage):
        self.m_file.write(
            f"<g transform='translate({self.m_size.x + img.m_margin}, {img.m_margin})'>\n"
        )
        self.m_file.write("\n".join(img.m_data))
        self.m_file.write("</g>\n")
        self.m_size = (
            self.m_size.x + img.m_size.x + 2 * img.m_margin,
            max(self.m_size.y, img.m_size.y + 2 * img.m_margin),
        )
